import { Component, OnInit } from "@angular/core";
import { StorageService } from "src/app/core/sotrage/storage.service";
import { Router, ActivatedRoute } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { MessageService } from "src/app/core/service/message.service";
import { ApiService } from 'src/app/core/api';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
    templateUrl: "./reportSubmit.html",
    styleUrls: ["./reportSubmit.scss"]
})
export class ReportSubmitComponent implements OnInit {
    validateForm: FormGroup;
    types = [{
        id: 'T1',
        name: '委托检测'
    }, {
        id: 'T2',
        name: '型式检测'
    }]
    classes = [];
    description;
    fileList = [];
    constructor(
        private api: ApiService,
        private route: ActivatedRoute,
        private router: Router,
        private msg: NzMessageService,
        private fb: FormBuilder
    ) {
        // this.initLoad();
    }
    typeShow;
    tabIndex=0;
    ngOnInit() {
        this.typeShow = this.route.snapshot.queryParams['type'];
        this.tabIndex = this.route.snapshot.queryParams['upData'];
       
        if (this.typeShow == 'Y') {
            this.validateForm = this.fb.group({
                testType: [null, [Validators.required]],// 检测类型: T1委托检测, T2型式检测
                porjuct: [null, [Validators.required]],// 项目编号 (/testItemListForOption.do中获取)
                contactName: [null, [Validators.required]],// 联系人
                contactTel: [null, [Validators.required]], // 联系电话
                enterpriseName: [null, [Validators.required]],// 企业名称
                productName: [null, [Validators.required]], // 产品名称
                // files: [null, [Validators.required]], // 文件
                // description: [null],// 描述
                modelNum: [null, [Validators.required]] // 产品型号
            });
        } else {
            this.validateForm = this.fb.group({
                contactName: [null, [Validators.required]],// 联系人
                contactTel: [null, [Validators.required]], // 联系电话
                enterpriseName: [null, [Validators.required]],// 企业名称
                productName: [null, [Validators.required]], // 产品名称
                modelNum: [null, [Validators.required]] // 产品型号
            });
        }
        const phone = this.route.snapshot.queryParams['phone'];
        this.route.snapshot.queryParams['phone'] ? this.validateForm.patchValue({contactTel:phone})  : null ;
        this.initLoad();
    }
    initLoad() {
        this.api.post('项目列表(选择框使用)', {}).then((res: any) => {
            this.classes = res.data.list;
        }).catch((res) => {
            this.msg.error(res.message);
        });
    }
    _sel_1;
    _sel_2;

    submitForm(data) {
        let files=[]
        for (let i = 0; i < this.fileList.length; i++) {
            files.push(this.fileList[i].value)
        }
        data.files = files+'';
        data.description = this.description+' ';
        let postUrl = this.typeShow == 'Y' ? '立即预约' : '检测定位';
        this.api.post( postUrl, data).then((res: any) => {
            this.router.navigateByUrl('/member/center/home/myProject');
        }).catch((res) => {
            this.msg.error(res.message);
        });
    }
    clSize = 1;
    clName = 'image';
    ev = 0;
    showLoading: Boolean = false;
    value:'';
    clUrl='/api//updateImage.do'
    propagateChange = (_: any) => {};
    uploadFile = (item) => {
        const file = item.file;
        const { name, size, type } = file;
        if (size > this.clSize * 1024 * 1024) {
            this.msg.error('图片大小超过限制,不能上传超过' + this.clSize + 'MB的图片');
            return;
        }
        const formData: any = new FormData();
        const xhr = new XMLHttpRequest();
        // formData.append('file', files);
        formData.append(this.clName, file);
        xhr.upload.onprogress = ev => {
            this.ev = parseInt((100 * ev.loaded) / ev.total + '');
        };
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                this.showLoading = false;
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.response);
                    this.value = data.data.url;
                    this.propagateChange(data.data.url);
                    this.fileList.push({value:this.value,name:file.name,size:file.size});
                } else {
                    item.value = null;
                }
            }
        };
        xhr.open('POST', this.clUrl, true);
        let token = localStorage.getItem('token');
        if(token){
            // token = JSON.parse(localStorage.getItem('token'));
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        }
        xhr.send(formData);
        this.showLoading = true;

    }
    getFileSize = (size) => {
        let s = parseFloat((size / 1024).toFixed(2));
        let a = "KB";
        if (s > 1024) {
            a = "MB";
            s = parseFloat((s / 1024).toFixed(2));
        }
        return s + a;
    }
}
